package com.xin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xin.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WYX
 * @create 2020-04-03-20:25
 */
@RestController
public class FastJsonDemo {

    @RequestMapping("/j4")
    public static void main(String[] args) {
        //创建对象
        User user1 =new User("韦余欣",1);
        User user2 =new User("韦余欣",2);
        User user3 =new User("韦余欣",3);
        User user4 =new User("韦余欣",4);
        List<User> userList =new ArrayList<User>();

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        System.out.println("=========java对象 转 json字符串=======");
        String str1= JSON.toJSONString(userList);
        System.out.println("JSON.toJSONString(userList)==>"+str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println("JSON.toJSONString(user1)==>"+str2);


        System.out.println("=========json字符串 转 java对象=======");
        User jp_user1=JSON.parseObject(str2,User.class);
        System.out.println("JSON.parseObject(str2,User.class)====>"+jp_user1);

        System.out.println("=========java对象 转 json对象=======");
        JSONObject jsonObject=(JSONObject) JSONObject.toJSON(user2);
        System.out.println("(JSONObject) JSONObject.toJSON(user2)===>"+jsonObject.getString("name"));

        System.out.println("=========json对象 转 java对象=======");
        User to_java_user=JSON.toJavaObject(jsonObject,User.class);
        System.out.println("JSON.toJavaObject(jsonObject,User.class)==>"+to_java_user);
    }
}
